<%@ Control Language="C#" AutoEventWireup="true" Codebehind="ProcessStatusControl.ascx.cs"
    Inherits="TeamTime.ProcessStatusControl" %>
<%--<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="false">
    <Services>
        <asp:ServiceReference Path="LongRunningProcesses.asmx" />
    </Services>
</asp:ScriptManager>--%>
<asp:Label ID="Label1" runat="server" Text=" "></asp:Label>
<asp:TextBox ID="txtGUID" runat="server" Style="display: none;"></asp:TextBox>
<asp:TextBox ID="txtNavigateToURLOnCompletion" runat="server" Style="display: none;"></asp:TextBox>
<asp:Button ID="btnCompleted" runat="server" Style="display: none;" OnClick="btnCompleted_Click" />
<div id="UpdateProgress1" style="display: none">
    <div id="ProgressTemplate1">
        <p style="text-align: center;">
            <asp:Label ID="lblProcessTitle" runat="server" Text="Process status"></asp:Label><br />
            <br />
            <img alt="Processing..." src="../images/ajaxloader.gif" />
        </p>
    </div>
    <div id="ProgressBar1">
        <br />
        <span id="Msg">...<br />
            <br />
            <br />
        </span>
    </div>
</div>
<style type="text/css">
        #UpdateProgress1
        {
            width: 350px; height:180px; background-color:#F8F8F8;
            top: 40%; left: 35%; position: absolute;
            border: solid 1px black;
        }
        #ProgressTemplate1
        {
            font-weight: bold; font-size: 9pt; color: navy; 
            font-family: Verdana; margin:10px; 
        }
        #Title1
        {
            font-size: 8pt; color: black; 
            font-family: Verdana; margin:5px; 
        }
        #ProgressBar1
        {
            font-size: 8pt; color: black; background-color:#FEFFFE;
            font-family: Verdana; text-align: center;
        }
        #Msg
        {
            font-size: 8pt; color: black; background-color:#FEFFFE;
            font-family: Verdana; font-weight: bold; 
        }
    </style>

<script type="text/javascript" id="progressMgr">
var progressManager = null;

// pageLoad()
// Called when the page is fully loaded. Use it to complete the initialization.
function pageLoad() {
   progressManager = new TN5Y.Progress();
}

// taskCompleted()
// Callback that signals that the remote method execution terminated.
function taskCompleted(results, context, methodName) {
    // Stop progress and reset UI
    progressManager.stopMonitor();
    updateUI(false);
    
    var navURL = document.getElementById('<% =txtNavigateToURLOnCompletion.ClientID%>').value;
    if (navURL !='')
    {
        window.navigate(navURL);
    }
    else
    {
        document.getElementById('<% =btnCompleted.ClientID%>').click(); //Fire off the invisible button click raise the Completed Event on the server.
    }
}

// taskFailed()
// Callback that signals that the remote method execution failed.
function taskFailed(results, context, methodName)
{
    $get("ctl00_ContentPlaceHolder1_ProcessStatusControl1_Label1").innerHTML = results;
    // Stop progress and reset UI
    progressManager.stopMonitor();
    updateUI(false);
}

// updateProgress()
// Callback function invoked when it is about time to update the progress bar.
// The progress client API invokes this function.
function updateProgress(result) {
    var res = result.split('~');
    var perc = res[1];
    if (perc=='') {perc=0;}
    var resMsg = res[0];
    var table = "<table width='100%'><tr><td colspan='2'>{2}</td></tr><tr><td bgcolor=blue width='{0}%'>";
    if (perc!='0') table +="{0}%";
    table +="</td><td width='{1}%'></td></tr></table>";
     table = String.format(table, perc, 100-perc, resMsg);
     $get("Msg").innerHTML = table;
}

// updateProgressCompleted()
// Callback function invoked when you have to reset the progress bar.
// The progress client API invokes this function.
function updateProgressCompleted() {
     $get("Msg").innerHTML = "No work done yet.<br /><br /><br />";
}

// updateUI()
// Page specific changes for UI during the task
function updateUI(showProgress) {
    var template = $get("UpdateProgress1");
    if (showProgress)
        template.style.display = "";
    else
        template.style.display = "none";
}

//---------------------------------------//
// Class declaration
// TN5Y.Progress :: 
//     Manage progress monitoring 

// Define the namespace of the class
Type.registerNamespace('TN5Y');

// Constructor
TN5Y.Progress = function TN5Y$Progress() 
{
    TN5Y.Progress.initializeBase(this);
    this._timerID = null;
    this._taskID = null;
    this._progressCallback = null;
    this._msInterval = null;
    this._callback = null;
}

// Start the timer to periodically check the status of the ongoing task
function TN5Y$Progress$startMonitor(taskID, msInterval, progressCallback, progressCompletedCallback) { 
    if (arguments.length !== 4) throw Error.parameterCount();
    
    // Update internal members
    _taskID = taskID;
    _msInterval = msInterval;
    _progressCallback = progressCallback;
    _progressCompletedCallback = progressCompletedCallback;
    
    this._startTimer();
}

// Stop the timer  
function TN5Y$Progress$stopMonitor() { 
    window.clearTimeout(_timerID);
    if (_progressCompletedCallback !== null)
        _progressCompletedCallback();    
}

//// Get task ID
//function TN5Y$Progress$getTaskID(taskID) { 
//    //return TN5Y.Random.getNumber(0, 10000000);
//    return guid();
//    
//}

//function S4() {
//   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
//}
//function guid() {
//   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
//}

// Start the timer to control progress
function TN5Y$Progress$_startTimer() {
    this._callback = Function.createDelegate(this, this._checkProgress);
    _timerID = window.setTimeout(this._callback, _msInterval);
}

// Modify the request to add the task ID to a hidden field (for UpdatePanel pages)
function TN5Y$Progress$modifyRequestForTaskId(request, taskID, hiddenField) {
    var body = request.get_body();
    var token = "&" + hiddenField + "=";
    body = body.replace(token, token + taskID);
    request.set_body(body);
    
    return request;
}

// Timer function(s)
function TN5Y$Progress$_checkProgress() {
    TeamTime.LongRunningProcesses.GetProcessStatus(_taskID, this._onFeedbackReceived, this._onFeedbackFailed, this);
}

function TN5Y$Progress$_onFeedbackReceived(results, context) {
    context._startTimer();
    if (_progressCallback !== null)
        _progressCallback(results);
}

function TN5Y$Progress$_onFeedbackFailed(results) {
}


// Class prototype
TN5Y.Progress.prototype = 
{
    
    startMonitor:           TN5Y$Progress$startMonitor,
    stopMonitor:            TN5Y$Progress$stopMonitor,
    modifyRequestForTaskId: TN5Y$Progress$modifyRequestForTaskId,
    _startTimer:            TN5Y$Progress$_startTimer,
    _checkProgress:         TN5Y$Progress$_checkProgress,
    _onFeedbackReceived:    TN5Y$Progress$_onFeedbackReceived,
    _onFeedbackFailed:      TN5Y$Progress$_onFeedbackFailed    
    
    //getTaskID:              TN5Y$Progress$getTaskID,
}

// Register the new class
TN5Y.Progress.registerClass('TN5Y.Progress');

////---------///
// function startTask() {  
//  // alert('Starting task...'); 
//   // Start the remote task using a Web service call
//   //var GUID = 'f4341ac0-e27b-4f64-b858-618409b9d2c7';
//   var GUID = document.getElementById('<% = txtGUID.ClientID%>').value;
////   alert(GUID);
////   PefcoIntranet.LongRunningProcesses.HelloWorld(taskCompletedX);
////PefcoIntranet.LongRunningProcesses.HelloWorld(taskCompletedX);
//   PefcoIntranet.LongRunningProcesses.ImportGreatPlainsOrders(GUID, taskCompleted, taskFailed);
//   // Turn on the progress monitor
//   updateUI(true); 
//   progressManager.startMonitor(GUID, 2000, updateProgress, updateProgressCompleted); 
//} 
 

</script>

